package com.yisu.expressway.onedollar.widget.addandsub;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.model.BuyNumConfigObj;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.PopupWindow;

/**
 * A subclass of {@link PopupWindow} to show a custom PopupWindow.
 */
public class JoinAddAndSubView extends AddAndSubView {
    private BuyNumConfigObj configObj;
    private OnBuyConfigListener onBuyConfigListener;
    public JoinAddAndSubView(Context context) {
        this(context, null);
    }

    public JoinAddAndSubView(Context context, AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public JoinAddAndSubView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    public BuyNumConfigObj getBuyNumConfig() {
        return configObj;
    }

    public void setGoodsNo(long goodsNo) {
        fetchBuyNumConfig(goodsNo);
    }

    public void setOnBuyConfigListener(OnBuyConfigListener onBuyConfigListener) {
        this.onBuyConfigListener = onBuyConfigListener;
    }

    private void fetchBuyNumConfig(long goodsNo) {
        if (goodsNo <= 0) {
            return;
        }
        Map<String, Object> params = new HashMap();

        params.put("goodsno", goodsNo);
        ApiClientHelper.postApi(ApiSetting.getBuyNumConfig(), new TypeToken<BuyNumConfigObj>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<BuyNumConfigObj>>() {
            @Override
            public void onResponse(ApiResult<BuyNumConfigObj> result) {
                if (!result.success) {
                    if (onBuyConfigListener != null) {
                        onBuyConfigListener.onBuyConfigGet(false, null);
                        setEnabled(false);
                    }
                    return;
                }
                setEnabled(true);
	            configObj = result.getResult();
                if (onBuyConfigListener != null) {
                    onBuyConfigListener.onBuyConfigGet(true, result.getResult());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                setEnabled(false);
                if (onBuyConfigListener != null) {
                    onBuyConfigListener.onBuyConfigGet(false, null);
                }

            }
        }, getContext());
    }

    public interface OnBuyConfigListener {
        void onBuyConfigGet(boolean bSuc, BuyNumConfigObj configObj);
    }
}
